package com.cloud.common.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * 应用上下文
 *
 * @author fengwenjin
 */
@Component
public class AppContext implements ApplicationContextAware {
    public static final String ENV_LOCAL = "local";
    public static final String ENV_PROD = "prod";

    static ApplicationContext applicationContext;

    public static String getAppName() {
        return getBean(Environment.class).getProperty("spring.application.name");
    }

    public static String getActiveEnv() {
        return getBean(Environment.class).getProperty("spring.profiles.active");
    }

    public static boolean isProdEnv() {
        String profileActive = getBean(Environment.class).getProperty("spring.profiles.active");
        return ENV_PROD.equals(profileActive);
    }

    public static boolean isLocalEnv() {
        String profileActive = getBean(Environment.class).getProperty("spring.profiles.active");
        return ENV_LOCAL.equals(profileActive);
    }

    public static Object getBean(String name) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBeansWithAnnotation(annotationType);
    }

    public static void publishEvent(ApplicationEvent event) {
        applicationContext.publishEvent(event);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppContext.applicationContext = applicationContext;
    }

}
